﻿using NLog;
using Susha.Areas.Admin;
using Susha.Areas.Default;
using Susha.Models;
using Susha.Models.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Script.Serialization;
using System.Web.Security;

namespace Susha
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        Logger _logger = LogManager.GetCurrentClassLogger();

        protected void Application_Start()
        {
            _logger.Info("=== App started ===");

            String currentDirectory = Directory.GetCurrentDirectory();
            String directory1 = Path.GetDirectoryName(Directory.GetCurrentDirectory());
            String directory2 = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));

            AdminAreaRegistration adminArea = new AdminAreaRegistration();
            AreaRegistrationContext adminAreaContext = new AreaRegistrationContext(adminArea.AreaName, RouteTable.Routes);
            adminArea.RegisterArea(adminAreaContext);

            DefaultAreaRegistration defaulArea = new DefaultAreaRegistration();
            AreaRegistrationContext defaultAreaContext = new AreaRegistrationContext(defaulArea.AreaName, RouteTable.Routes);
            defaulArea.RegisterArea(defaultAreaContext);

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies[CommonTools.COOKIE_NAME];

            if (cookie != null && !String.IsNullOrWhiteSpace(cookie.Value))
            {
                try
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    UserSerializeModel serializeModel = serializer.Deserialize<UserSerializeModel>(ticket.UserData);

                    UserClass newUser = new UserClass(ticket.Name);
                    newUser.Id = serializeModel.UserId;
                    newUser.Email = serializeModel.Email;
                    newUser.Role = serializeModel.Role;

                    HttpContext.Current.User = newUser;
                }
                catch (Exception ex)
                {
                    _logger.Error(String.Format("Application_PostAuthenticateRequest(): {0}", ex.Message));
                }
            }
        }
    }
}